package git.soulbgm;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.net.InetSocketAddress;

/**
 * TCP客户端处理数据类
 *
 * @author SoulBGM
 * @date 2022/04/20 00:08
 */
@ChannelHandler.Sharable
public class TcpClientHandle extends SimpleChannelInboundHandler<ByteBuf>  {

    private final LogUtil log = new LogUtil(getClass());

    /**
     * 当客户端连接时调用
     *
     * @param ctx 通道处理程序上下文
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    /**
     * 当客户端连接断开时调用
     *
     * @param ctx 通道处理程序上下文
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Channel channel = ctx.channel();
        InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
        String ip = address.getAddress().getHostAddress();
        int port = address.getPort();
        clearChannelFuture(ip, port);
        connectionRetry(ip, port);
    }

    /**
     * 清除通道
     *
     * @param ip 地址
     */
    private void clearChannelFuture(String ip, int port) {
        TcpClient.remove(ip, port);
    }

    /**
     * 连接重试
     *
     * @param ip   地址
     * @param port 端口
     */
    private void connectionRetry(String ip, int port) {
        TcpClient client = TcpClient.getClient();
        client.warn("IP:{}, 端口:{} 连接断开，正在连接重试~~", ip, port);
        client.connect(ip, port);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        // 发送数据IP
        String ip = insocket.getAddress().getHostAddress();
        // 接收的端口
        int connectPort = insocket.getPort();
        // 数据
        byte[] data = ByteBufUtil.getBytes(msg);
        if (data == null) {
            return;
        }
        NtpdateUtil.handleNtpPacket(data);
    }

}
